package pe.com.jubre.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class FilterAutenticar extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private FilterConfig filterConfig = null;

	@Override
	public void destroy() {
		this.filterConfig = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest hRequest = (HttpServletRequest) request;
		HttpSession session = ((HttpServletRequest) request).getSession();

		String url = hRequest.getRequestURL().toString();

		int length = url.length();
		String html = url.substring(length - 4, length);
		String jsp = url.substring(length - 3, length);
		
		String urlIndex = "";
		String urlLogin = "";
		if((html.equalsIgnoreCase("html") || jsp.equalsIgnoreCase("jsp"))&& !url.equalsIgnoreCase(urlIndex)){
			if(session.getAttribute("user") != null){
				chain.doFilter(request, response);
			}else{
				((HttpServletResponse)response).sendRedirect(urlLogin);
			}			
		}else{
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	
}
